iT邦幫忙

0

筆記 - Laravel-MultiAuthGuard 多重身份組

  • 分享至 

  • xImage
  •  

參考資料:

目的

使 Laravel 除了原本 User 資料表外的資料表也可以當作紀錄登入資訊使用。

一、 建立資料表

使用指令建立資料表:

php artisan make:migration create_admins_table

資料表內容如下:

public function up()
{
	Schema::create('admins', function (Blueprint $table) {
		$table->id();
		$table->string('name');	
		$table->string('username')->unique();	
		$table->string('password');	
		$table->rememberToken();	
		$table->timestamps();	
	});
}

二、建立 Model

使用指令建立 Model:

php artisan make:model Admin

Model 內引入 Illuminate\Foundation\Auth\User 後將 extends 改為 Authenticatable,並設置 $guard,完整內容如下:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{
    use HasFactory;

    protected $guard = 'admin';

    protected $fillable = [
        'name', 'username', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
}

三、定義 guards

打開 config/auth.php,並新增新的 guard 與 provider:

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
    ],
        ...
        
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],
    ],

四、透用 Seeder 新增帳號

使用指令建立 Seeder:

php artisan make:seeder CreateAdmin 

打開 database/seeders/CreateAdmin.php,並加入:

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

...

public function run()
{
	DB::table('admins')->insert([
		'name' => 'admin',
		'username' => 'admin',
		'password' => Hash::make('123456'),
	]);
}

然後運行上面寫的 Seeder:

php artisan db:seed --class=CreateAdmin

五、建立登入

這邊以 Livewire 為例:

namespace App\Http\Livewire\Auth;

use Livewire\Component;
use Illuminate\Support\Facades\Auth;

class Login extends Component
{
    public $username;
    public $password;
    public $remember = false;

    protected $rules = [
        'username' => 'required',
        'password' => 'required|min:6',
    ];

    public function login()
    {
        if (Auth::guard('admin')->attempt($this->validate(), $this->remember)) {
            // 登入成功
            return redirect('/posts');
        }
    }

    public function render()
    {
        return view('livewire.auth.login')
            ->layout('layouts.base');
    }
}

六、限制路由

開啟 routes/web.php,並把要登入才能看得頁面套上 middleware:

Route::middleware(['auth:admin', 'auth.session'])->group(function () {
    Route::get('/posts', App\Http\Livewire\Post\ShowPostList::class);
});

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言